//
//  XJHomeCellViewModel.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/20.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import SDWebImage
import YYText
import SVProgressHUD

class XJHomeCellViewModel: NSObject {
    
    var status: XJHomeStatusModel? {
        
        didSet{
            
            dealMemberImage()
            dealSourceText()            
            if let s = status?.retweeted_status {
                
                if let name = s.user?.name,content = s.text {
                    
                    retweetText = "@\(name):\(content)"
                    reweetAttributedStr = self.attributedText(retweetText!)
                }
            }
            retweetPictureViewSize = calPictureViewSize(status?.retweeted_status?.pic_urls)
            originalPictureViewSize = calPictureViewSize(status?.pic_urls)
            createDate = self.sinaDate(status?.created_at)
            
            originalAttributedStr = self.attributedText(status?.text ?? "")
            
        }
    }
    
    //会员图标
    var memberImage: UIImage?
    // 转发微博的内容
    var retweetText: String?
    //来源
    var sourceText: String?
    //配图视图大小
    var retweetPictureViewSize: CGSize = CGSizeZero
    //原创视图大小
    var originalPictureViewSize: CGSize = CGSizeZero
    
    //原创微博副文本
    var originalAttributedStr: NSAttributedString?
    //转发微博副文本
    var reweetAttributedStr: NSAttributedString?
    

    // 处理首页微博图片表情&特殊字符高亮
    func attributedText(text: String) -> NSAttributedString{
    
        //原生的副文本
        let attributedStr = NSMutableAttributedString(string: text)
        
        var result = [XJMatchResrult]()
        
        //匹配出表情字符串
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]") { (count, captureString, captureRange, _) -> Void in
            
            print("\(captureString.memory)-----\(captureRange.memory)")
            
            let res = XJMatchResrult(captureString: captureString.memory!, captureRange: captureRange.memory)
            result.append(res)
        }
        //防止越界,倒着遍历
        for value in result.reverse() {
        
            //通过表情字符串找到对应的表情模型
            if let emoticon = XJEmojiKeyboardViewModel.sharedEmojiViewModel.emoticonWithChs(value.captureString as String) {
                
                print(emoticon)
            
                let s = "\(emoticon.fileName ?? "")/\(emoticon.png ?? "")"
                let img = UIImage(named: s, inBundle: XJEmojiKeyboardViewModel.sharedEmojiViewModel.emotionBundle, compatibleWithTraitCollection: nil)
//                
                let font = UIFont.systemFontOfSize(contentLabelFont)
                let attr = NSMutableAttributedString.yy_attachmentStringWithContent(img, contentMode: .ScaleAspectFill, attachmentSize: CGSize(width: font.lineHeight, height: font.lineHeight), alignToFont: font, alignment: .Center)
//                 // 初始化文字附件
//                let attachment = XJTextAttachment()
//                attachment.image = img
//                let font = UIFont.systemFontOfSize(contentLabelFont)
//                
//                attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
//                
//                // 初始化一个富文本
//                let attr = NSAttributedString(attachment: attachment)
                
                attributedStr.replaceCharactersInRange(value.captureRange, withAttributedString: attr)
                
            }
        }
        //添加字体颜色
        attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, attributedStr.length))
        
        // 添加特殊字符文字颜色
        // 话题
        addLinkColor("#[^#]+#", attributedStr: attributedStr)
        // @
        addLinkColor("@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+", attributedStr: attributedStr)
        // url
        addLinkColor("([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", attributedStr: attributedStr)
        
        //添加字体
        attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(contentLabelFont), range: NSMakeRange(0, attributedStr.length))

        return attributedStr
    }
    
    
    
    
    /// 添加特殊字符的颜色
    func addLinkColor(regex: String, attributedStr: NSMutableAttributedString){
        
        (attributedStr.string as NSString).enumerateStringsMatchedByRegex(regex) { (_, captureString, captureRange, _) -> Void in
            
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1), range: captureRange.memory)
            
            //初始化背景对象
            let border = YYTextBorder(fillColor: UIColor(red: 177/255, green: 215/255, blue: 255/255, alpha: 1), cornerRadius: 3)
            border.insets = UIEdgeInsetsZero
            
            //初始化高亮对象
            let highlight = YYTextHighlight()
            highlight.setColor(UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1))
            highlight.setBackgroundBorder(border)
            
            let s = (captureString.memory) as! String
            highlight.tapAction =  {(containerView: UIView, text: NSAttributedString, range: NSRange, rect: CGRect) -> () in
                
                print("特殊字符点击了")
                
                SVProgressHUD.showInfoWithStatus(s)
                
            }
            attributedStr.yy_setTextHighlight(highlight, range: captureRange.memory)
            
        }
    }
    
    
    //时间label
    var createAtText: String?{
    
        return dealCreatAtText(createDate ?? NSDate());
    }
    
    //微博创建时间
    private var createDate: NSDate?
    
    /**
     格式化时间字符串
     */
    private func sinaDate(createAt: String?)->NSDate? {
    
        guard let create_at = createAt else {
            return nil
        }
        let fm = NSDateFormatter()
        fm.locale = NSLocale(localeIdentifier: "en")
        fm.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        let createDate = fm.dateFromString(create_at)
        return createDate
        
    }
    /**
     *  时间处理
     */
    
    private func dealCreatAtText(createDate: NSDate) -> String {
        
        let fm = NSDateFormatter()
        fm.locale = NSLocale(localeIdentifier: "en")
        
        let calendar = NSCalendar.currentCalendar()
        
        //与当前时间对比
        if isDateInThisYear(createDate){//是否是今年
            
            if calendar.isDateInToday(createDate){//今天
                let currentDate = NSDate()
                //当前时间与创建时间的时间差
                let timeInterval = currentDate.timeIntervalSinceDate(createDate)
                
                if timeInterval < 60{//1分钟之内
                    return "刚刚"
                }else if timeInterval < 3600 {//1小时之内
                
                    return"\(Int(timeInterval)/60)分钟前"
                }else{//xxx小时前
                
                    return "\(Int(timeInterval)/3600)小时前"
                }
            
            }else if calendar.isDateInYesterday(createDate){//昨天
                fm.dateFormat = "昨天 HH:mm"
                return fm.stringFromDate(createDate)
            
            }else{//其他
            
                fm.dateFormat = "MM-dd HH:mm"
                return fm.stringFromDate(createDate)
            }
        
        }else{//不是今年
        
            fm.dateFormat = "yyyy-MM-dd HH:mm"
            return fm.stringFromDate(createDate)
        }
    }
    
    //判断是否是当前时间的年份
    private func isDateInThisYear(targetDate: NSDate) -> Bool {
    
        let currentDate = NSDate()
        let fm = NSDateFormatter()
        fm.dateFormat = "yyyy"
        
        let currentYear = fm.stringFromDate(currentDate)
        let targetYear = fm.stringFromDate(targetDate)
        
        return currentYear == targetYear
    }
    
    /**
     更新单图视图大小
     */
    func updateSingeImgSize() {
        retweetPictureViewSize = calSingleImgSize(status?.retweeted_status?.pic_urls)
        originalPictureViewSize = calSingleImgSize(status?.pic_urls)
        
    }
    
    /**
     计算单张图片大小
    */
    private func calSingleImgSize (thumbnail_pic: [XJStatusUserInfo]?) -> (CGSize) {
    
        //取出图片地址
        guard let imgUrl = thumbnail_pic?.first?.thumbnail_pic else{
            return CGSizeZero
        }
//        print(imgUrl)
        
        //根据地址取出已下载好的图片(从缓存中取)
        if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imgUrl) {
        
            //图片处理
            let scale = UIScreen.mainScreen().scale
            var size = CGSizeMake(image.size.width * scale, image.size.height * scale)
            
            //过宽处理 如果宽度小于 50 ，把其图片宽度拉伸到50，高度等比例拉伸
            if size.width < 70 {
            
                size.width = 70
                let height = 70 / size.width * size.height
                size.height = height > 100 ? 100 : height
            }
            
            return size
        }
        
        return CGSizeZero
    }
    
    /**
     计算配图视图大小
     */
     
    private func calPictureViewSize(thumbnail_pic: [XJStatusUserInfo]?) -> (CGSize) {
    
        let count = thumbnail_pic?.count ?? 0
        if count == 0 {
            return CGSizeZero
        }
        
        let col = count == 4 ? 2 : (count > 3 ? 3 :count)
        let row = ((count - 1)/3) + 1
        
        let width = CGFloat(col) * XJStatusPictureItemWH + CGFloat(col - 1) * XJStatusPictureItemMargin
        let height = CGFloat(row) * XJStatusPictureItemWH + CGFloat(row - 1) * XJStatusPictureItemMargin
        
        return CGSizeMake(width, height)
    }
    
    /**
     会员等级
     */
    private func dealMemberImage() {
        
        if let rank = status?.user?.mbrank where (rank > 0 && rank < 7) {
            
            memberImage = UIImage(named: "common_icon_membership_level\(rank)")
        }
    }
    /**
     来源处理
     */
    private func dealSourceText() {
        
        guard let source = status?.source else{
            
            return
        }
        // <a href=\"http://app.weibo.com/t/feed/5B6hUc\" rel=\"nofollow\">iPhone 6s Plus</a>
        
        //截取字符串
        if let startIndex = source.rangeOfString("\">")?.endIndex, endIndex = source.rangeOfString("</")?.startIndex {
            
            let res = source.substringWithRange(startIndex..<endIndex)
            sourceText = "来自\(res)"
        }
        
    }
    
    
}
